<template>
  <el-dialog
    title="任务详情"
    :width="formProps.dialogWidth"
    :close-on-click-modal="false"
    v-model="dialogShow"
    append-to-body
    :before-close="closeDialog"
  >
    <template #title>
      <div>
        <span class="mr-10" style="font-weight: bolder">任务详情</span>
        <el-tooltip effect="light" content="刷新" placement="bottom">
          <el-button
            plain
            :type="['info', 'warning'][refreshType]"
            circle
            size="small"
            :loading="refreshLoading"
            @click="refreshDetail"
            :disabled="refreshCroDisabled"
            :icon="Refresh"
          ></el-button>
        </el-tooltip>
      </div>
    </template>
    <div style="">
      <div class="mb-10" v-loading="dataLoading">
        <template v-if="data">
          <label-item :dataCloumns="dataCloumns" :data="data">
            <template #C_Status="{ key }">
              <el-tag :type="returnTypeOrLabelName(key, true)">{{ returnTypeOrLabelName(key) }}</el-tag>
            </template>
            <template #C_TaskSource="{ key }">
              <div>{{ returnTypeOrLabelName(key) }}</div>
            </template>
          </label-item>
        </template>
        <template v-if="!data && !dataLoading">
          <span>数据错误!请联系管理员!</span>
        </template>
      </div>
      <z-table :list="list" :columns="columns" :tableProps="tableProps" :tableLoading="tableLoading">
        <template #content="{ row, key }">
          <el-tag v-if="key == 'Status'" :type="statusOptions.find((x) => x.value == row[key]).tagType">{{
            statusOptions.find((x) => x.value == row[key]).label || ''
          }}</el-tag>
          <span v-else>{{ row[key] }}</span>
        </template>
      </z-table>
      <div class="mt-10">
        <el-button
          :disabled="refreshBtnCroDisabled || ![0, 1, 2].includes(data.Status || 0)"
          :icon="VideoPause"
          @click="pauseBtnclick"
          :loading="pauseLoading"
          type="warning"
          >暂停</el-button
        >
        <el-button
          :disabled="refreshBtnCroDisabled || data.Status != 3"
          :icon="VideoPlay"
          :loading="nextLoading"
          @click="nextBtnclick"
          type="success"
          >继续执行</el-button
        >
        <el-button
          :disabled="refreshBtnCroDisabled || data.Status != 3"
          :icon="CircleClose"
          @click="cancelBtnclick"
          :loading="cancelLoading"
          type="info"
          >取消任务</el-button
        >
        <el-button
          :disabled="refreshBtnCroDisabled || data.Status != 3"
          :icon="CircleCheck"
          :loading="bindLoading"
          @click="bindBtnclick"
          type="danger"
          >强制完成</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { Refresh, VideoPause, VideoPlay, CircleClose, CircleCheck } from '@element-plus/icons-vue'
</script>
<script>
// 设备子任务运行详情列表
import ZTable from '@/views/_common/table.vue'
import LabelItem from '@/components/LabelItem'
import _ from 'lodash'
export default {
  name: 'driver-detail-dialog',
  components: {
    ZTable,
    LabelItem,
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    query: { type: [Number, String], default: '' },
    isAutoRequst: { type: Boolean, default: false },
    controTime: { type: Number, default: 5 },
    controlBtnDisabledShow: { type: Boolean, default: false },
  },
  watch: {
    modelValue: {
      handler(val) {
        if (val) {
          this.init()
          if (this.isAutoRequst) this.autoReuqestAction()
        } else {
          if (this.isAutoRequestTimer) {
            clearInterval(this.isAutoRequestTimer)
            this.isAutoRequestTimer = null
          }
        }
      },
      immediate: true,
    },
  },
  computed: {
    dialogShow: {
      get() {
        return this.modelValue
      },
      set(val) {
        this.$emit('update:modelValue', val)
      },
    },
    refreshType: function () {
      return Number(!this.refreshLoading)
    },
    // 刷新机制
    refreshCroDisabled: function () {
      return (
        this.tableLoading ||
        this.dataLoading ||
        this.refreshLoading ||
        this.pauseLoading ||
        this.nextLoading ||
        this.cancelLoading ||
        this.bindLoading
      )
    },
    // 按钮刷新机制
    refreshBtnCroDisabled: function () {
      return (
        this.tableLoading ||
        this.dataLoading ||
        this.refreshLoading ||
        this.pauseLoading ||
        this.nextLoading ||
        this.cancelLoading ||
        this.bindLoading ||
        this.controlBtnDisabled
      )
    },
  },
  data() {
    return {
      formProps: {
        dialogWidth: '80%',
      },
      tableProps: {
        border: true,
        hideOperations: true,
        // opsColWith: 140, //不定义默认80
        // showSelection: true, // 是否开启复选
        // expandable: true, //是否展开行
        // showIndexCol: false, //是否显示索引列
        // indexColWidth: 50, //索引列宽度
      },
      columns: [
        { title: '编号', key: 'Ordering', width: 65 },
        { title: '任务号', key: 'ActionNo' },
        { title: '优先级', key: 'Priority', width: 80 },
        { title: '起始位置编码', key: 'StartLocationUserCode', width: 120 },
        { title: '起始执行设备', key: 'StartLocationDeviceName', width: 120 },
        { title: '结束位置编码', key: 'EndLocationUserCode', width: 120 },
        { title: '结束执行设备', key: 'EndLocationDeviceName', width: 120 },
        { title: '状态', key: 'Status', width: 90 },
        { title: '创建时间', key: 'CreatedAt' },
        { title: '发送时间', key: 'SentAt' },
        { title: '完成时间', key: 'FinishedAt' },
        { title: '设备信息', key: 'DeviceStatus' },
      ],
      sourceOptions: [
        { label: '未知', value: 0 },
        { label: 'WCS', value: 1 },
        { label: 'WMS', value: 2 },
      ],
      statusOptions: [
        { label: '新任务', value: 0, tagType: 'primary' },
        { label: '已发送', value: 1, tagType: 'success' },
        { label: '正在运行', value: 2, tagType: 'success' },
        { label: '暂停', value: 3, tagType: 'warning' },
        { label: '发生错误', value: 4, tagType: 'danger' },
        { label: '被取消', value: 5, tagType: 'info' },
        { label: '已完成', value: 6, tagType: 'success' },
        { label: '强制暂停', value: 9, tagType: 'warning' },
      ],
      dataCloumns: [
        {
          title: '任务号',
          key: 'TaskCode',
          format: (col, data, key, value) => {
            return data.TaskDetailId + '#' + data.TaskCode
          },
        },
        {
          title: '任务来源',
          key: 'TaskSource',
        },
        { title: '任务状态', key: 'Status' },
        {
          title: '起始位置',
          key: 'StartLocationUserCode',
          format: (col, data, key, value) => {
            return data.StartLocationUserCode + '@' + data.StartLocationDeviceName
          },
        },
        {
          title: '结束位置',
          key: 'EndLocationUserCode',
          format: (col, data, key, value) => {
            return data.EndLocationUserCode + '@' + data.EndLocationDeviceName
          },
        },
        {
          title: '当前位置',
          key: 'CurrentLocationUserCode',
          format: (col, data, key, value) => {
            return data.CurrentLocationUserCode + '@' + data.CurrentLocationDeviceName
          },
        },
        {
          title: '优先级',
          key: 'Priority',
        },
        {
          title: '创建时间',
          key: 'CreatedAt',
        },
        {
          title: '完成时间',
          key: 'FinishedAt',
        },
        {
          title: '托盘号',
          key: 'Barcode',
        },
      ],
      dataLoading: false,
      data: {
        Status: 0,
      },
      tableLoading: false,
      list: [],
      submitLoading: false,
      refreshLoading: false,
      // 按钮loading
      pauseLoading: false,
      nextLoading: false,
      cancelLoading: false,
      bindLoading: false,
      // 控制规定时间内不执行操作需要再次刷新的控制枢纽
      controlBtnDisabled: false,
      // 是否在更新状态下关闭容器时，传递更新事件
      isAutoResearch: false,
      isAutoRequestTimer: null,
    }
  },
  created() {},
  destroyed() {
    if (this.isAutoRequestTimer) {
      clearInterval(this.isAutoRequestTimer)
      this.isAutoRequestTimer = null
    }
  },
  methods: {
    // 返回相对应的字符串
    returnTypeOrLabelName(key, isType = false) {
      switch (key) {
        case 'Status':
          if (isType) {
            return this.statusOptions.find((x) => x.value == this.data[key])?.tagType || 'info'
          } else {
            return this.statusOptions.find((x) => x.value == this.data[key])?.label || ''
          }
        case 'TaskSource':
          if (isType) {
            return this.sourceOptions.find((x) => x.value == this.data[key])?.tagType || 'info'
          } else {
            return this.sourceOptions.find((x) => x.value == this.data[key])?.label || ''
          }
      }
    },
    // 刷新
    refreshDetail() {
      this.refreshLoading = true
      this.init()
    },
    // 创建可持续化
    setControlBtn() {},
    // 创建接口自动触发
    autoReuqestAction() {
      if (this.isAutoRequestTimer) {
        return
      }
      this.isAutoRequestTimer = setInterval(() => {
        this.init()
      }, 1000 * this.controTime)
    },
    // 初始化
    init() {
      this.controlBtnDisabled = false
      this.setControlBtn()
      this.dataLoading = true
      this.tableLoading = true
      if (!this.query) {
        this.dataLoading = false
        this.tableLoading = false
        return
      }
      this.getTableList()
      this.getData()
      setTimeout(() => {
        this.refreshLoading = false
      })
    },
    formatList(data) {
      let datac = [...data]
      let tmp = datac.reverse().find((i) => i.Status != 5 || i.Status != 6)
      if (!!tmp) {
        this.http
          .get(this.$api.wcsUrl + 'wcs/DeviceDescription/GetDeviceDescription', {
            deviceName: tmp.StartLocationDeviceName,
          })
          .then((r) => {
            tmp.DeviceStatus = `${r?.CovertTime} - ${r?.DeviceName} - ${r?.Msg}`
          })
      }
      return data.map((x) => {
        return x
      })
    },
    formatData(data) {
      let tmp = _.cloneDeep(data)
      return tmp
    },
    // 获取list
    getTableList() {
      this.http
        .get(this.$api.wcsUrl + 'wcs/task/GetEquipmentAction?taskDetailId=' + this.query)
        .then((r) => {
          this.list = this.formatList(r)
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    // 获取数据
    getData() {
      this.http
        .get(this.$api.wcsUrl + 'wcs/task/GetDetailTasksById?taskDetailId=' + this.query)
        .then((r) => {
          if (r) {
            this.data = this.formatData(r)
            console.log(this.data)
          } else {
            this.$message.info('任务已完成')
            this.$emit('update:modelValue', false)
          }
        })
        .finally(() => {
          this.dataLoading = false
        })
    },
    closeDialog() {
      if (this.isAutoRequestTimer) {
        clearInterval(this.isAutoRequestTimer)
        this.isAutoRequestTimer = null
      }
      this.$emit('update:modelValue', false)
      this.$emit('statusSuccesCallBack')
    },
    // 暂停
    pauseBtnclick() {
      this.pauseLoading = true
      this.http
        .post(this.$api.wcsUrl + 'wcs/task/SuspendTaskDet', { taskcode: this.data.TaskDetailId })
        .then((r) => {
          this.$message.success('暂停成功')
          this.refreshDetail()
          this.isAutoResearch = true
        })
        .finally(() => {
          this.pauseLoading = false
        })
    },
    // 继续执行
    nextBtnclick() {
      this.nextLoading = true
      this.http
        .post(this.$api.wcsUrl + 'wcs/task/ContExecTaskDet', { taskcode: this.data.TaskDetailId })
        .then((r) => {
          this.$message.success('执行成功')
          this.refreshDetail()
          this.isAutoResearch = true
        })
        .finally(() => {
          this.nextLoading = false
        })
    },
    // 取消任务
    cancelBtnclick() {
      this.cancelLoading = true
      this.http
        .post(this.$api.wcsUrl + 'wcs/task/CancelTaskDet', { taskcode: this.data.TaskDetailId })
        .then((r) => {
          this.$message.success('取消成功')
          this.refreshDetail()
          this.isAutoResearch = true
        })
        .finally(() => {
          this.cancelLoading = false
        })
    },
    // 强制执行
    bindBtnclick() {
      this.bindLoading = true
      this.http
        .post(this.$api.wcsUrl + 'wcs/task/ForceFinishTaskDet', { taskcode: this.data.TaskDetailId })
        .then((r) => {
          this.$message.success('执行成功')
          this.refreshDetail()
          this.isAutoResearch = true
        })
        .finally(() => {
          this.bindLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped></style>
